import { z } from 'zod';

const passwordField = z
  .string()
  .min(6, { message: '密码至少需要 6 个字符。' })
  .regex(/[A-Z]/, {
    message: '密码至少包含 1 个大写字母。',
  })
  .regex(/[0-9]/, {
    message: '密码至少包含 1 个数字。',
  });

// Schema for requesting a password reset email
export const getResetRequestSchema = () => {
  return z.object({
    email: z
      .string()
      .email({ message: '请输入合法的邮箱地址。' })
      .min(1, { message: '邮箱为必填项。' }),
  });
};

// Schema for setting a new password via reset token
export const getResetPasswordWithTokenSchema = (hasPrefilledToken = false) => {
  const baseSchema = z
    .object({
      password: passwordField,
      confirmPassword: z
        .string()
        .min(1, { message: '请再次输入新密码。' }),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: '两次输入的密码不一致。',
      path: ['confirmPassword'],
    });

  if (hasPrefilledToken) {
    return baseSchema;
  }

  return baseSchema.extend({
    token: z.string().min(1, { message: '请填写重置令牌。' }),
  });
};

// Schema for changing password while signed in
export const getChangePasswordSchema = () => {
  return z
    .object({
      currentPassword: z
        .string()
        .min(1, { message: '请输入当前密码。' }),
      newPassword: passwordField,
      confirmPassword: z
        .string()
        .min(1, { message: '请再次输入新密码。' }),
    })
    .refine(
      (data) => data.newPassword === data.confirmPassword,
      {
        message: '两次输入的新密码不一致。',
        path: ['confirmPassword'],
      },
    )
    .refine(
      (data) => data.currentPassword !== data.newPassword,
      {
        message: '新密码不能与当前密码相同。',
        path: ['newPassword'],
      },
    );
};

